const staticAssets = ["./", "./index.html"];

self.addEventListener("install", async (event) => {
  const cache = await caches.open("news-static");
  cache.addAll(staticAssets);
});

self.addEventListener("fetch", (event) => {
  const req = event.request;
  const url = new URL(req.url);
  if (url.origin == location.origin) {
    event.respondWith(cacheFirst(req));
  } else {
    event.respondWith(networkFirst(req));
  }
});

async function cacheFirst(req) {
  const cachedRespone = await caches.match(req);
  return cachedRespone || networkFirst(req);
}

async function networkFirst(req) {
  const cache = await caches.open("news-dynamic");
  try {
    const res = await fetch(req);
    cache.put(req, res.clone());
    return res;
  } catch (error) {
    const cachedRespone = await cache.match(req);
    return cachedRespone || (await caches.match("./fallback.json"));
  }
}
